package com.hyy.netty.c2;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;

@Slf4j
public class EventLoopServer {
    public static void main(String[] args) {
        //细分2：创建一个独立的EventLoopGroup
        EventLoopGroup group = new DefaultEventLoopGroup();

        //1、启动器，负责组装netty组件，启动服务器
        new ServerBootstrap()
                //2、BossEventLoop，WorkEventLoop(selector,thread)，group 组
                //细分1：boss 只负责 ServerSocketChannel 上的accept事件 worker 只负责 socketChannel上的读写
                .group(new NioEventLoopGroup(),new NioEventLoopGroup(2))
                //3、选择 服务器 ServerSocketChannel的实现类
                .channel(NioServerSocketChannel.class)
                //4、boss 负责处理连接 worker(child) 负责处理读写，决定了worker(child) 能执行哪些操作(handler)
                .childHandler(
                        //5、channel 代表和客户端进行数据读写的通道，Initializer 初始化，负责添加别的handler
                        new ChannelInitializer<NioSocketChannel>() {
                            @Override
                            protected void initChannel(NioSocketChannel ch) throws Exception {
                                //6、添加具体的handler
                                ch.pipeline().addLast("handler1",new ChannelInboundHandlerAdapter(){//自定义 handler
                                    //处理读事件
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        ByteBuf buf = (ByteBuf) msg;
                                        String s = buf.toString(Charset.defaultCharset());
                                        log.debug("handler1 channelRead -- {}",s);
                                        //将消息传给下个handler
                                        ctx.fireChannelRead(msg);
                                    }
                                }).addLast(group,"handler2",new ChannelInboundHandlerAdapter(){//自定义 handler
                                    //处理读事件
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        ByteBuf buf = (ByteBuf) msg;
                                        String s = buf.toString(Charset.defaultCharset());
                                        log.debug("handler2 channelRead -- {}",s);
                                    }
                                });
                            }
                        })
                //7、绑定监听端口
                .bind(8080);

    }
}
